<?php

namespace app\admin\controller\pms;

use app\admin\model\Reservation;
use app\common\controller\Backend;
use app\common\model\Category;
use think\Db;

/**
 * 客栈订单信息
 *
 * @icon fa fa-circle-o
 */
class Pmsorderinfo extends Backend
{

    /**
     * Pmsorderinfo模型对象
     * @var \app\admin\model\Pmsorderinfo
     */
    protected $model = null;
    protected $prefix = '';

    protected $noNeedLogin = [];

    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
        $this->model  = new \app\admin\model\Pmsorderinfo;
        $this->prefix = config('database.prefix');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $a    = new \app\admin\model\Admin;
        $resi = new \app\admin\model\Reservation();
        $ri   = new \app\admin\model\Pmsroominfo;
        $opl  = new \app\admin\model\Pmsorderpeoplelist;
        // $op     = new \app\admin\model\Pmsorderpayment;
        $prefix = $this->prefix;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                // ->fetchSql()
                ->paginate($limit);
            // echo $list;die;
            $rows = $list->items();
            foreach ($rows as $i => $item) {
                $list[$i]['reserve_no'] = '';
                /*if ($item['reserve_id']) {
                    $m                      = $resi->field('id,reserve_no')->where('id', $item['reserve_id'])->find();
                    $list[$i]['reserve_no'] = $m['reserve_no'];
                }*/

                $oplData         = $opl->field('id,realname,sex,tel')->where('order_id', $item['id'])->find();
                $list[$i]['tel'] = $oplData['tel'];

                $m = $ri->alias('ri')
                    ->field('ri.id,ri.room_no,rt.name')
                    ->join($prefix . 'pms_room_type rt', 'ri.room_type = rt.id')
                    ->where('ri.id', $item['room_info_id'])
                    ->find();

                $list[$i]['room_no']        = $m ? $m['room_no'] : '';
                $list[$i]['room_type_name'] = $m ? $m['name'] : '';

                //收款
                // $payment_total             = $op->where('order_id', $item['id'])->where('state', 0)->sum('money');
                // $list[$i]['payment_total'] = $payment_total;

                $m                                = $a->where('id', $item['last_editor'])->find();
                $list[$i]['last_editor_nickname'] = $m ? $m['nickname'] : '';
            }
            return json(["total" => $list->total(), "rows" => $rows]);
        }
        return $this->view->fetch();
    }


    /**
     * 订单详情
     */
    public function detail($ids = null)
    {
        $a   = new \app\admin\model\Admin;
        $ri  = new \app\admin\model\Pmsroominfo;
        $rt  = new \app\admin\model\Pmsroomtype;
        $opl = new \app\admin\model\Pmsorderpeoplelist;
        $op  = new \app\admin\model\Pmsorderpayment;
        $conf                  = new \app\admin\model\Pmsconfig;
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $row['reserve_no'] = '-';
        if ($row['reserve_id']) {
            $m                   = Db::name('reservation')->field('id,accompany_name,create_time')->where('id', $row['reserve_id'])->find();
            $row['reserve_info'] = $m['accompany_name'] . ' - ' . $m['create_time'];
        }

        $row['birthday']       = date('Y-m-d', $row['birthday']);
        $row['check_in_date']  = date('Y-m-d H:i:s', $row['check_in_time']);
        $row['check_out_date'] = date('Y-m-d H:i:s', $row['check_out_time']);

        $row['sex_name'] = '女生';
        if ($row['sex'] == 1) {
            $row['sex_name'] = '男生';
        }

        $row['room_type_name'] = '未知';
        if ($row['room_type_id']) {
            $m                     = $rt->where('id', $row['room_type_id'])->find();
            $row['room_type_name'] = $m ? $m['name'] : '未知';
        }

        $row['room_no'] = '未知房号';
        if ($row['room_info_id']) {
            $m              = $ri->where('id', $row['room_info_id'])->find();
            $row['room_no'] = $m ? $m['room_no'] : '未知房号';
        }

        $row['order_status_name'] = $this->model->get_order_status_name($row['order_status']);

        $row['birthday_text']       = $row['birthday'];
        $row['check_in_time_text']  = date('Y-m-d H:i:s', $row['check_in_time']);
        $row['check_out_time_text'] = date('Y-m-d H:i:s', $row['check_out_time']);

        //收款
        $opList = $op->where('order_id', $row['id'])->select();
        foreach ($opList as $i => $item) {
            $opList[$i]['addons_list']          = $item['addons'] ? explode(',', $item['addons']) : '';
            $opList[$i]['updatetime_txt']       = date('Y-m-d H:i:s', $item['updatetime']);
            $m                                  = $a->where('id', $item['last_editor'])->find();
            $opList[$i]['last_editor_nickname'] = $m ? $m['nickname'] : '';
        }

        $oplList = $opl->where('order_id', $row['id'])->where('state', 0)->select();
        if (count($oplList)) {
            foreach ($oplList as $i => $item) {
                $oplList[$i]['sex_class'] = 'label-danger';
                $oplList[$i]['sex_name']  = '女士';
                if ($item['sex']) {
                    $oplList[$i]['sex_class'] = 'label-info';
                    $oplList[$i]['sex_name']  = '先生';
                }
            }
        }

        $row['room_info'] = $row['room_info_id'] . ',' . $row['room_type_id'];

        $room = (new \app\admin\model\Pmsroominfo())->queryBookableRoomsByDate($row['check_in_time'], $row['check_out_time']);

        foreach ($room as &$item) {
            $item['room_info'] = $item['id'] . ',' . $item['room_type'];
        }

        $this->view->assign('cancel', (int)(in_array($row['order_status'],[0,-1]) && (date('Y-m-d') < date('Y-m-d', $row['check_in_time']))));

        $this->view->assign('roomList', $room);
        $this->view->assign("row", $row);
        $this->view->assign("opList", $opList);
        $this->view->assign("oplList", $oplList);

        $diseaseCate          = (new Category())->field('id,name,type,flag')->where(['pid' => 14])->select()->toArray();
        $diseaseId            = $row['disease_id'];
        foreach ($diseaseCate as $item1) {
            if ($item['id'] == $diseaseId) {
                $oiModel['disease_cate'] = $item1['name'];
            }
        }
        $this->assign("category", $diseaseCate);

        $this->view->assign("certificatestypeList", $conf->selectpage('certificates_type'));

        return $this->view->fetch();
    }

    public function changeRoom($id)
    {
        $params = $this->request->post();
        if (!$id) {
            $this->error(__('订单不存在'));
        }
        $roomList = [['id' => $params['room_info_id'], 'room_type' => $params['room_type_id']]];
        try {
            (new Reservation())->checkStayRoom($roomList, $params['check_in_time'], $params['check_out_time']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->model->where(['id' => $id])->update([
            'order_invalid_memo' => $params['remarks'],
            'room_info_id'       => $params['room_info_id'],
            'room_type_id'       => $params['room_type_id']
        ]);

        (new \app\admin\model\Pmseventlogs())->insert([
            'res_type'   => 'order',
            'res_id'     => $id,
            'res_no'     => $params['order_no'],
            'event_type' => 'edit-room',
            'detail'     => json_encode(['description' => $this->auth->nickname . '更换床位：' . $params['room_info_text'], '理由:' . $params['remarks']], 320),
            'state'      => 0,
            'createtime' => time(),
            'creator'    => $this->auth->id
        ]);
        $this->success('换床成功！');
    }

    public function cancel(int $id)
    {
        $this->model->where(['id' => $id])->update(['order_status' => 2]);
        $this->success('取消成功！');
    }
}
